package aop.xyz.myapp.service.account;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import aop.xyz.myapp.PessimisticLockingFailureException;
import aop.xyz.myapp.dao.account.UserDAO;
import aop.xyz.myapp.domain.account.User;

public class UserManager implements IUserManager{
	Logger log = LoggerFactory.getLogger(this.getClass());
	private static final int DEFAULT_MAX_RETIES = 2;
	
	/**
	 * When a DB lock exception occurred, how many times retry the operation  
	 */
	private Integer maxRetries = DEFAULT_MAX_RETIES;

	private UserDAO userDao;
	
	public void saveUser(User user){
		int numAttempts = 0;
		do {
			numAttempts ++;
			try {
				userDao.saveOrUpdate(user);
				break;
			} catch (PessimisticLockingFailureException e) {
				if (numAttempts >= maxRetries){
					throw new RuntimeException("Save user failed.");
				}
			}			
		} while(true);
	}

	public User getUser(Long id) {
		return userDao.get(id);
	}

	public User delUser(Long id) {
		return userDao.del(id);
	}

	public List<User> delUsers(List<Long> ids) {
		return userDao.del(ids);
	}

	public List<User> getAllUser() {
		return userDao.getAll();
	}

	public void delUser(User user) {
		userDao.del(user);
	}

	public void setUserDao(UserDAO userDao) {
		this.userDao = userDao;
	}

	public UserDAO getUserDao() {
		return userDao;
	}

	public void setMaxRetries(Integer maxRetries) {
		this.maxRetries = maxRetries;
	}

	public Integer getMaxRetries() {
		return maxRetries;
	}

}
